<template>
    <div class="container">
        <div class="chat-record-box">
            <el-button type="success" style="margin-top: 10px;" plain @click="addNewChat">添加新会话</el-button>
            <template v-for="(chatRecord,index) in chatRecords" :key="chatRecord.chatId">
                <div :class="{'chat-record-item': true, 'active-chat': chatRecord.id == activeChat }"  @click="getChatMessages(chatRecord.id)">
                    {{ chatRecord.title }}
                </div>
            </template>
        </div>
        <div class="dialog-box">
            <t-chat ref="chatRef" :clear-history="true" :reverse="false" :text-loading="loading" :data="messages"
                @scroll="handleChatScroll" @clear="clearConfirm">
                <!-- eslint-disable vue/no-unused-vars -->
                <template #name="{ item, index }">
                    {{ item.name }}
                </template>
                <template #avatar="{ item, index }">
                    <el-avatar v-if="item.role == 'assistant'" size="28"
                        src="https://tdesign.gtimg.com/site/chat-avatar.png" fit="cover" />
                    <el-avatar v-if="item.role == 'user'" size="28" src="https://tdesign.gtimg.com/site/avatar.jpg"
                        fit="cover" />
                </template>
                <template #datetime="{ item, index }">
                    {{ item.datetime }}
                </template>
                <template #content="{ item, index }">
                    <t-chat-content :content="item.content" />
                </template>
                <template #footer>
                    <t-chat-input :stop-disabled="isStreamLoad" @send="inputEnter" @stop="handleStop"> </t-chat-input>
                </template>
            </t-chat>
            <t-button v-show="isShowToBottom" variant="text" class="bottomBtn" @click="backBottom">
                <div class="to-bottom">
                    <ArrowDownIcon />
                </div>
            </t-button>
        </div>
    </div>

</template>
<script setup>
import axiosInstance from '@/utils/request';
import { ElMessage } from 'element-plus'
import { ref, onMounted } from 'vue';
import { ArrowDownIcon } from 'tdesign-icons-vue-next';
import axios from 'axios';
const chatRecords = ref([])
const activeChat = ref(1)
const messages = ref([
    {
        avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
        name: '小智',
        datetime: '今天16:38',
        content: '🤖 嘘——悄悄告诉你，和我聊天的宝子都会变聪明！不信？试试发个题目过来！(๑¯◡¯๑)',
        role: 'assistant',
    }])
const loading = ref(false);
const isStreamLoad = ref(false);
const chatRef = ref(null);
const isShowToBottom = ref(false);
let socket = null
//添加新会话
const addNewChat = async () => {
    const res = await axios.post('http://localhost:8121/api/chat/create', {
        title: new Date().toLocaleDateString () + ' 新会话'
    },{
        withCredentials:true
    })
    if (res.data.code == 0) {
        ElMessage.success('创建新会话成功')
        loadChatRecord()
        activeChatRecordId.value = res.data.data
    }else{
        ElMessage.error(res.data.message)
    }
}
// 滚动到底部
const backBottom = () => {
    chatRef.value.scrollToBottom({
        behavior: 'smooth',
    });
};
// 是否显示回到底部按钮
const handleChatScroll = function ({ e }) {
    //   console.log(e.target.scrollTop)
    //   const scrollTop = e.target.scrollTop;
    //   isShowToBottom.value = scrollTop < e.target.scrollHeight;
    const container = e.target
    // 计算距离底部的阈值（这里设置50px缓冲）
    const threshold = 50
    const isNearBottom =
        container.scrollHeight - container.scrollTop - container.clientHeight <= threshold

    // 当不在底部区域时显示按钮
    isShowToBottom.value = !isNearBottom
};
const loadChatRecord = async () => {
    const res = await axiosInstance.get('/chat/page')
    console.log(res);
    chatRecords.value = res.records
    const chatId = chatRecords.value.at(-1).id;
    socket = new WebSocket(`ws://localhost:8121/api/aiWs/` + chatRecords.value.at(-1).id);
    activeChat.value = chatId
    getChatMessages(chatId)
    //连接成功
    socket.onopen = (event) => {
        console.log(chatId, "连接成功！")
    }
    // 接收消息
    socket.onmessage = (event) => {
        console.log("AI 回复:", event.data);
        if (event.data == '[end]')
            return;
        messages.value[messages.value.length - 1].content += event.data
    };
}
onMounted(async () => {
    const res = await axiosInstance.get('/chat/page')
    console.log(res);
    chatRecords.value = res.records
    const chatId = chatRecords.value.at(-1).id;
    socket = new WebSocket(`ws://localhost:8121/api/aiWs/` + chatRecords.value.at(-1).id);
    activeChat.value = chatId
    getChatMessages(chatId)

    //连接成功
    socket.onopen = (event) => {
        console.log(chatId, "连接成功！")
    }
    // 接收消息
    socket.onmessage = (event) => {
        console.log("AI 回复:", event.data);
        if (event.data == '[end]')
            return;
        messages.value[messages.value.length - 1].content += event.data
    };
})

//清空历史消息
const clearConfirm = async () => {
    const res = await axiosInstance.post('/chat/message/clean', { id: activeChat.value })
    if (res)
        ElMessage({
            message: '清空历史记录成功',
            type: 'success',
        })
    else
        ElMessage.error('清空历史记录失败')
    messages.value = []
}
const handleStop = function () {
    isStreamLoad.value = false;
};



const getChatMessages = async (chatId) => {
    console.log('chatId', chatId)
    activeChat.value = chatId;
    socket.close()
    socket = new WebSocket(`ws://localhost:8121/api/aiWs/` + chatId);
    //连接成功
    socket.onopen = (event) => {
        console.log(chatId, "连接成功！")
    }
    // 接收消息
    socket.onmessage = (event) => {
        console.log("AI 回复:", event.data);
        if (event.data == '[end]')
            return;
        messages.value[messages.value.length - 1].content += event.data
    };
    const res = await axiosInstance.get('/chat/message/list?chatId=' + chatId);
    console.log('/chat/message/list', res)
    messages.value = res.map(msg => {
        return {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: msg.role == 'assistant' ? '小智' : 'YOU',
            datetime: new Date(msg.createTime).toLocaleDateString(),
            content: msg.content,
            role: msg.role,
        }
    })
}
// 发送消息
const inputEnter = async function (inputValue) {
    if (isStreamLoad.value) {
        return;
    }
    if (!inputValue) return;
    messages.value.push({
        avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
        name: '我',
        datetime: '今天3:38',
        content: inputValue,
        role: 'user',
    })
    // isStreamLoad.value = true;
    // loading.value = true;
    messages.value.push({
        name: '小智',
        datetime: '今天3:38',
        content: '',
        role: 'assistant',
    })
    socket.send(inputValue);
    // loading.value = false;
    // isStreamLoad.value = false;
};


</script>


<style scoped>
.container {
    width: 100%;
    display: flex;
    justify-content: center;

}

.chat-record-box {
    height: 85vh;
    width: 30vh;
    display: flex;
    flex-direction: column;
    align-items: center;

    color: rgb(147, 147, 147);
    background-color: rgb(255, 255, 255);
    border: 1px solid rgb(219, 216, 216);
    border-radius: 10px;
    margin-right: 20px;

}

.chat-record-item {
    width: 90%;
    height: 20px;
    border-radius: 10px;
    border: 1px solid rgb(219, 216, 216);
    margin-top: 10px;
    overflow: hidden;
    padding: 5px 2px 5px 2px;
    text-align: center;
    transition: box-shadow 0.3s ease;
    
}

.chat-record-item:hover {
    box-shadow: 0 10px 20px rgba(235, 234, 234, 0.19), 0 6px 6px rgba(190, 189, 189, 0.23);
    background-color: rgb(219, 234, 254);
    cursor: default;
}
.active-chat{
    background-color: rgb(219, 234, 254);
}
.dialog-box {
    position: relative;
    height: 85vh;
    width: 100vh;
    box-sizing: border-box;
    padding: 20px 10px 10px 10px;
    background-color: rgb(255, 255, 255);
    border: 1px solid rgb(219, 216, 216);
    border-radius: 10px;
}

.bottomBtn {
    position: absolute;
    left: 50%;
    margin-left: -20px;
    bottom: 150px;
    padding: 0;
    border: 0;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    box-shadow: 0px 8px 10px -5px rgba(0, 0, 0, 0.08), 0px 16px 24px 2px rgba(0, 0, 0, 0.04),
        0px 6px 30px 5px rgba(0, 0, 0, 0.05);
}

.to-bottom {
    width: 40px;
    height: 40px;
    border: 1px solid #dcdcdc;
    box-sizing: border-box;
    background: var(--td-bg-color-container);
    border-radius: 50%;
    font-size: 24px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.t-icon {
    font-size: 24px;
}
</style>